package com.wenwen.social.application.listeners;

import com.wenwen.social.application.event.MessageCreateEvent;
import com.wenwen.social.domain.model.*;
import com.wenwen.social.domain.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

@Component
public class MessageCreateListener {
	@Autowired
	private UserService userService;
	@Autowired
	private PersonLineService personLineService;
	@Autowired
	private HomeLineService homeLineService;
	@Autowired
	private FollowService followService;
	@Autowired
	private FansService fansService;
	@Autowired
	private FollowLineService followLineService;
	/**
	 * 更新用户已发送信息数
	 * @param event
	 */
	@Async
	@EventListener
	public void updateMsgNum(MessageCreateEvent event)
	{
		Long uid = event.getMessage().getUid();
		User user = userService.getUser(uid);
		if(user == null) return;
		Long messages = user.getMessages();
		if(messages != null){
			user.setMessages(messages+1);
			userService.updateUser(user);
		}
	}
	@Async
	@EventListener
	public void personLineAdd(MessageCreateEvent event)
	{
		Message message = event.getMessage();
		Long uid = message.getUid();
		Long id = message.getId();
		Long time = message.getTime();
		personLineService.add(uid,new PersonLine(id,time));
	}
	@Async
	@EventListener
	public void homeLineAdd(MessageCreateEvent event)
	{
		Message message = event.getMessage();
		Long uid = message.getUid();
		Long id = message.getId();
		Long time = message.getTime();
		//更新主页时间线
		homeLineService.add(uid,new HomeLine(id,time));
	}
	@Async
	@EventListener
	public void followLineAdd(MessageCreateEvent event)
	{
		Message message = event.getMessage();
		Long uid = message.getUid();
		Long id = message.getId();
		Long time = message.getTime();
		//更新关注时间线(查找哪些人关注了uid,然后更新)
		add2FollowLine(uid,id,time);
	}
	private void add2FollowLine(Long userId, Long messageId, Long now) {
		Fans fans = fansService.queryFans(userId, 1, -1);
		if(fans == null) return;
		Map<Long, Long> followMap = fans.getFansMap();
		if (followMap == null || followMap.isEmpty()) return;
		Set<Long> fansIds = followMap.keySet();
		followLineService.add(fansIds,new FollowLine(messageId,now));
	}
}
